import serial.tools.list_ports
import binascii
import serial
ports = serial.tools.list_ports.comports()

def str_to_hex_int(hex_str):
    # 去掉字符串中的 "0x" 前缀
    # cleaned_str = hex_str.lower().replace("0x", "")
    # 将十六进制字符串转换为整数
    # return int(cleaned_str, 16)

    return int(hex_str, 16)

def recv(serial):
    global data
    while True:
        data = serial.read(30)
        if data == '':
            continue
        else:
            break
        sleep(0.02)
    return data

for port in ports:
    print(port.device, port.description, "---", hex(port.vid), hex(port.pid))
    # print()
    # print( hex(str_to_hex_int("0x10c4")))
    # print(type(port.vid))
    # print(port.vid, "---", str_to_hex_int("0x10c4"))


for port in ports:
    #比较VID和PID
    if (port.vid == str_to_hex_int("0x10c4")) and \
            (port.pid == str_to_hex_int("0xEA60")):
        print("port name", port.name)


        try:
            com = serial.Serial(port.name, 115200, timeout=0.5)

            print("Serial open")
            while True:
                data = recv(com)
                print(data)
        # 打开串口失败
        except serial.SerialException as e:
            print("open serial error:", e)